package com.ruoyi.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.KeyValidate;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.enums.HttpMethod;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.filter.PropertyPreExcludeFilter;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysConfigService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

/**
 * 操作日志记录处理
 * 
 * @author ruoyi
 */
@Aspect
@Component
public class KeyValidateAspect
{

    @Autowired
    private ISysConfigService sysConfigService;

    //     配置织入点
    @Pointcut("@annotation(com.ruoyi.common.annotation.KeyValidate)")
    public void keyValidatePointCut()
    {
    }

    @Before("keyValidatePointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable
    {
        KeyValidate keyValidate = getAnnotationKeyValidate(joinPoint);

        String parameter = ServletUtils.getRequest().getParameter(keyValidate.paramName());
        if (StringUtils.isEmpty(parameter)){

            try {
                String inputLine = ServletUtils.getRequest().getReader().readLine();
                ServletUtils.getRequest().getReader().close();
                JSONObject jsonObject = JSON.parseObject(inputLine);
                if (jsonObject.containsKey(keyValidate.paramName())){
                    parameter = jsonObject.getString(keyValidate.paramName());
                }else {
                    throw new ServiceException("请传入key值");
                }
            }catch (Exception e){
                throw new ServiceException("请传入key值");
            }
        }
        String tokenValue = sysConfigService.selectConfigByKey(keyValidate.deviceToken());
        if (!parameter.equalsIgnoreCase(tokenValue)){
            throw new ServiceException("key校验失败");
        }
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(keyValidate)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, KeyValidate keyValidate, Object jsonResult)
    {
    }

    /**
     * 拦截异常操作
     * 
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "@annotation(keyValidate)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, KeyValidate keyValidate, Exception e)
    {
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private KeyValidate getAnnotationKeyValidate(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(KeyValidate.class);
        }
        return null;
    }
}
